package com.yun.algorithmproblem.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Leetcode18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        dfs(4, 0, nums.length - 1, target, nums,
                new LinkedList<>(), result);
        return result;
    }

    private void dfs(int n, int i, int j, long target, int[] nums,
                     LinkedList<Integer> stack,
                     List<List<Integer>> result) {
        if (n == 2) {
            //套用两数之和求解
            twoSum(i, j, nums, target, stack, result);
            return;
        }
        for (int k = i; k < j - n + 2; k++) {
            if (k > i && nums[k] == nums[k - 1]) {
                continue;
            }
            stack.push(nums[k]);
            dfs(n - 1, k + 1, j, target - nums[k], nums, stack, result);
            stack.pop();
        }
    }

    private void twoSum(int i, int j, int[] nums, long target,
                        LinkedList<Integer> stack,
                        List<List<Integer>> result) {
        while (i < j) {
            long sum = (long) nums[i] + (long) nums[j]; // 使用long类型防止溢出
            if (sum < target) {
                i++;
            } else if (sum > target) {
                j--;
            } else {
                ArrayList<Integer> list = new ArrayList<>(stack);
                list.add(nums[i]);
                list.add(nums[j]);
                result.add(list);
                j--;
                i++;
                while (i < j && nums[i] == nums[i - 1]) {
                    i++;
                }
                while (i < j && nums[j] == nums[j + 1]) {
                    j--;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {2, 2, 2, 2, 2};
        int target = 8;
        List<List<Integer>> result = new Leetcode18().fourSum(nums, target);
        for (List<Integer> list : result) {
            System.out.println(list);
        }
    }
}
